package com.bocai.kelalacar.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;


import com.bocai.kelalacar.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 作者 yuanfei on 2016/11/14.
 * 邮箱 yuanfei221@126.com
 */

public class DBManager {
    private final int BUFFER_SIZE = 400000;
    public static final String DB_NAME = "bnt_districts.db"; //保存的数据库文件名
    public static final String PACKAGE_NAME = "com.bocai.kelalacar";
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"
            + PACKAGE_NAME+"/databases";  //在手机里存放数据库的位置

    private SQLiteDatabase database;
    private Context context;
    private File cacheFile;

    public DBManager(Context context) {
        this.context = context;
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }

    public SQLiteDatabase openDatabase() {
        return this.database;
    }

    public static SQLiteDatabase getDatabase(){
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME,
                null);
        return db;
    }

    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            if ((int)SP.get(context,"database",1) != 2) { //判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
                new File(DB_PATH).mkdirs();
                cacheFile = new File(DB_PATH,DB_NAME);//设置参数  
                cacheFile.createNewFile();//生成文件
                InputStream is = this.context.getResources().openRawResource(R.raw.bnt_districts); //欲导入的数据库

                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
                SP.put(context,"database",2);
            }
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                    null);
            return db;
        } catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }

    public void closeDatabase() {
        this.database.close();
    }
}
